let heartCheck = {
  timeout: 30000,
  timeoutObj: null,
  serverTimeoutObj: null,
  reset: function() {
    clearTimeout(this.timeoutObj);
    clearTimeout(this.serverTimeoutObj);
    return this;
  },
  start: function() {
    this.timeoutObj = setTimeout(() => {
      // console.log("发送ping");
      wx.sendSocketMessage({
        data: 'eyJ0eXBlIjoxLCJkYXRhIjoicGluZyJ9',
        success() {
          // console.log("发送ping成功");
        },
        fail(){
          
        }
      });

    }, this.timeout);
  }
};
var zzk_date =  0;
var common = require("../../public");
var url = common.url;
var APP_ID = common.APP_ID;
var md5 = common.md5Start;
var utilMd5 = require('../../utils/md5');


Page({
  data: {
    adds_zzk: 0,
    networkType:"",
    heise:true,
    heise1:true,
    last_data_zzk: 0,
    zzk: true,
    zzk_data: "",
    warend: false,
    windowHeight: 654,
    maxtime: "",
    isHiddenLoading: true,
    isHiddenToast: true,
    dataList: {},
    djsj: 0,
    daojishi: 2,
    zhanchangshuju: [],
    inputvalue: '',
    war_id: '',
    scoreid: '',
    hongbaoxinxi: [], //红包信息
    showModal: false, //输入密码弹窗  false隐藏 true显示
    zhanchangxinxi: false,
    zhanchanghongbao: false,
    zhongjiang: false,
    wuzi: false,
    wz: [],
    hbxx: [],
    userpas: '',
    yuyue: false, //预约进攻弹窗 false隐藏 true显示
    is_shield: 0, //护盾 1需要 0不需要
    jingongcishu: 0, //预约的进攻次数
    diyici: 1,
    listss: [], //滚动区域聊天内容   someone==1 别人说  2：自己说
    use_hudun: false, //是否使用护盾，true：使用   false:不用护盾
    liu_enter_alert: true, //游戏指南弹框
  },
  // 1秒延迟
  heise:function(aaa){
    wx.vibrateLong();
    clearTimeout(this.add)
    if(aaa){
      this.setData({
        heise: false
      })
    this.add = setTimeout(() => {
        this.setData({
          heise: true
        })
      }, 1000)
    } else{
        this.setData({
          heise: false,
          heise1: false
        })
     this.add=setTimeout(() => {
        this.setData({
          heise: true,
          heise1:true
        })
      }, 1000)
      }
    
  },
  //跳转商品详情
  go_goodDetail: function(e) {
    var goodid = e.currentTarget.dataset.id; //商品id
    wx.navigateTo({
      url: '../gooddetail/gooddetail?comefrom=1&id=' + goodid,
    })
  },
  // 拍卖成功跳转订单列表
  handle_pay: function(e) {
    wx.navigateTo({
      url: '../orderlist/orderlist?num=3',
    })
  },
  //隐藏游戏指南弹框
  hide_enter_field: function(e) {
    this.setData({
      liu_enter_alert: false
    })
  },
  //输入 发送消息框 获取焦点事件
  inputfocusTap: function(e) {
    this.setData({
      inputfocus: true
    })
  },
  //输入 发送消息框 失去焦点事件
  inputblurTap: function(e) {
    // console.log("失去焦点")
    this.setData({
      inputfocus: false
    })
  },
  base64_encode: function(str) { // 编码，配合encodeURIComponent使用
    str = escape(str);
    var c1, c2, c3;
    var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var i = 0,
      len = str.length,
      strin = '';
    while (i < len) {
      c1 = str.charCodeAt(i++) & 0xff;
      if (i == len) {
        strin += base64EncodeChars.charAt(c1 >> 2);
        strin += base64EncodeChars.charAt((c1 & 0x3) << 4);
        strin += "==";
        break;
      }
      c2 = str.charCodeAt(i++);
      if (i == len) {
        strin += base64EncodeChars.charAt(c1 >> 2);
        strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        strin += base64EncodeChars.charAt((c2 & 0xF) << 2);
        strin += "=";
        break;
      }
      c3 = str.charCodeAt(i++);
      strin += base64EncodeChars.charAt(c1 >> 2);
      strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
      strin += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
      strin += base64EncodeChars.charAt(c3 & 0x3F)
    }
    // console.log(strin)
    return strin
  },

  base64_decode: function(input) { // 解码，配合decodeURIComponent使用

    var that = this;
    var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    while (i < input.length) {
      enc1 = base64EncodeChars.indexOf(input.charAt(i++));
      enc2 = base64EncodeChars.indexOf(input.charAt(i++));
      enc3 = base64EncodeChars.indexOf(input.charAt(i++));
      enc4 = base64EncodeChars.indexOf(input.charAt(i++));
      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;
      output = output + String.fromCharCode(chr1);
      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
      }
    }
    return that.utf8_decode(output);
  },
  utf8_decode: function(utftext) { // utf-8解码
    var string = '';
    let i = 0;
    let c = 0;
    let c1 = 0;
    let c2 = 0;
    while (i < utftext.length) {
      c = utftext.charCodeAt(i);
      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      } else if ((c > 191) && (c < 224)) {
        c1 = utftext.charCodeAt(i + 1);
        string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
        i += 2;
      } else {
        c1 = utftext.charCodeAt(i + 1);
        c2 = utftext.charCodeAt(i + 2);
        string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
        i += 3;
      }
    }
    return string;
  },
  //点击进攻按钮
  dianjijingong: function(e) {
    var that = this;
    var heise = this.data.heise;
  if(heise){

    if (e.target.dataset.count <= 0) {
      wx.showModal({
        content: '您已没有弹药，是否去购买？',
        showCancel: true,
        cancelText: '取消',
        confirmText: '确定',
        success: function(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '../daoju/daoju',
              success: function(res) {}
            })
          } else if (res.cancel) {}
        }
      })
      //没有道具跳转购买道具页面

    } else {
      // 如果有进攻次数，判断是否选择了使用护盾
      var session_str = wx.getStorageSync('session_str');
      var shuju = {}; //数据

      var shuju1 = {
        type: 3,
        session_str: session_str,
        war_id: that.data.war_id
      }

      shuju1 = that.base64_encode(JSON.stringify(shuju1));
      wx.sendSocketMessage({
        data: shuju1,
        fail() {
          that.reconnect()
        }
      });
    }
    this.shuaxinshuju();
    this.heise(121);
  }
  },
  // 点击护盾
  dianjihudun: function(e) {
    var that = this;
    var heise = this.data.heise1;
    if (heise) {
    if (e.target.dataset.count <= 0) {
      wx.showModal({
        title: '提示',
        content: '您已没有护盾，是否去购买？',
        showCancel: true,
        cancelText: '取消',
        confirmText: '确定',
        success: function(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '../daoju/daoju',
              success: function(res) {}
            })
          } else if (res.cancel) {}
        }
      })
    } else {
      // var use_hudun = this.data.use_hudun;//是否使用护盾 true:使用  false:不用护盾
      // use_hudun = !use_hudun;
      // this.setData({
      // 	use_hudun: use_hudun
      // })
      var shuju = {
        type: 3,
        session_str: wx.getStorageSync('session_str'),
        war_id: this.data.war_id,
        is_shield: 1
      }
      shuju = this.base64_encode(JSON.stringify(shuju));
      wx.sendSocketMessage({
        data: shuju,
        fail() {
          that.reconnect()
        }
      });
    }
    this.shuaxinshuju();
      this.heise();
    }
  },

  dianjizhadan: function(e) {
    var that = this;
    var heise = this.data.heise;
    if (heise) {
    if (e.target.dataset.count <= 0) {
      wx.showModal({
        content: '您已没有炸弹，是否去购买？',
        showCancel: true,
        cancelText: '取消',
        confirmText: '确定',
        success: function(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: 'pages/daoju/daoju',
              success: function(res) {}
            })
          } else if (res.cancel) {}
        }
      })
    } else {
      var shuju = {
        type: 4,
        session_str: wx.getStorageSync('session_str'),
        war_id: this.data.war_id,
      }
      shuju = this.base64_encode(JSON.stringify(shuju));
      wx.sendSocketMessage({
        data: shuju,
        fail() {
          that.reconnect()
        }
      });
    }
    this.shuaxinshuju();
      this.heise();
    }
  },
  //战场结束提示
  warendtap: function() {
    wx.showToast({
      title: '战场已结束',
      icon: 'none',
      mask: true,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  // 用户输入框输入内容
  yonghushuru: function(e) {
    var that =this;
    var inputvalue = e.detail.value; //用户输入内容
    var inputVallueStr = inputvalue.trim(); //用户输入内容去掉首尾空格
    if (!inputVallueStr) { //如果用户输入空字符串，则不进行后续操作
      this.setData({
        inputvalue: ''
      });
      return false;
    }
    var shuju = {
      type: 2,
      msg: e.detail.value,
      session_str: wx.getStorageSync('session_str'),
      war_id: this.data.war_id
    }
    shuju = this.base64_encode(JSON.stringify(shuju));
    // console.log(shuju)
    wx.sendSocketMessage({
      data: shuju,
      fail() {
        that.reconnect()
      }
    });
    this.setData({
      inputvalue: '',
      zzk: 1
    });
    this.inputblurTap();
  },
  add0: function(m) {
    return m < 10 ? '0' + m : m
  },
  format: function(shijianchuo) {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    // return y + '-' + this.add0(m) + '-' + this.add0(d) + ' ' + this.add0(h) + ':' + this.add0(mm) + ':' + this.add0(s);
    return this.add0(m) + '-' + this.add0(d) + ' ' + this.add0(h) + ':' + this.add0(mm);
  },

  //事件处理函数
  onShow: function(e) {
    let that = this;
    clearTimeout(that.zzk_adds)
    clearTimeout(that.zzk_add)
   var war_id = this.data.war_id;
    wx.startAccelerometer({
      interval: 'game'
    })
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    var session_str = wx.getStorageSync('session_str');
    if (!session_str) {
      wx.navigateTo({
        url: '../author/author',
      })
      return false;
    }
    wx.request({
      url: url+'War/warInfo',
      data: {
        war_id: war_id,
        session_str: session_str
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        that.setData({
          zzk_data: res.data.data,
          last_bullet_count: res.data.data.last_bullet_count, //剩余进攻次数
          max_bullet_count: res.data.data.max_bullet_count, //最大进攻次数
          current_time: res.data.data.current_time, //服务器时间
          max_bomb_count: res.data.data.max_bomb_count, //最大空袭数（本场）
          max_shield_count: res.data.data.max_shield_count, //最大护盾数（本场）
        })
        wx.setNavigationBarTitle({
          title: res.data.data.war_name
        })
        that.daojishijisuan(res.data.data);
        if (res.data.data.start_time > timestamp) {
          res.data.data.start_time = that.format(res.data.data.start_time * 1000);
          that.setData({
            daojishi: 2
          })
        } else {
          res.data.data.start_time = that.format(res.data.data.start_time * 1000);
          that.setData({
            daojishi: 1
          })
        }
        if (res.data.data.is_pwd == 1) {
          // 加入战场需要密码
          that.shurumima();
          that.setData({
            zhanchangxinxi: false
          })
        } else {
          that.linkSocket();
          var war_id = that.data.war_id;
          wx.request({
            url: 'https://master.shoppingwar.cn/api/War/joinWar',
            data: {
              war_id: war_id,
              session_str: wx.getStorageSync('session_str')
            },
            method: 'POST',
            dataType: 'json',
            responseType: 'text',
            success: function (res) {
              if (res.data.code == 200) {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 2000
                });
                that.linkSocket();
                that.hideModal();
                // ========================
              } else {
                const wxCurrPage = getCurrentPages(); //获取当前页面的页面栈
                const wxPrevPage = wxCurrPage[wxCurrPage.length - 2]; //获取上级页面的page对象
                if (wxPrevPage) {
                  //修改上级页面的数据
                  wxPrevPage.setData({
                    zzk: 2,
                    bwl: res.data.msg //baseData为上级页面的某个数据
                  })
                }
                that.setData({
                  warend: true, //战场结束标志
                })
              }
            },
            fail: function (res) { },
          })
        }
        that.setData({
          zhanchangshuju: res.data.data,
         
        });
        clearInterval(that.interval);
        that.qudaojishi();
        var session_str = wx.getStorageSync('session_str'); //密钥
        var war_id = that.data.war_id;
        wx.request({
          url: url + 'War/userPropCount',
          data: {
            session_str: session_str,
            war_id: war_id,
            APP_ID: APP_ID,
            sign: md5([
              "session_str" + session_str,
              "war_id" + war_id,
              "APP_ID" + APP_ID,
            ])
          },
          header: {},
          method: 'post',
          dataType: 'json',
          responseType: 'text',
          success: function (res) {
            wx.hideLoading();
            if (res.data.code == 200) {
              var max_bullet_count = that.data.max_bullet_count; //最大进攻次数
              var left_duobao = max_bullet_count - res.data.data.last_bullet_count; //剩余进攻次数
              var have_bullet_count = res.data.data.have_bullet_count;//用户剩余夺宝次数
              left_duobao = left_duobao - have_bullet_count < 0 ? left_duobao : have_bullet_count;//选择最小的夺宝次数
              console.log(have_bullet_count)
              console.log(left_duobao)
              var bomb_count = res.data.data.bomb_count; //用户剩余空袭数
              var shield_count = res.data.data.shield_count; //用户剩余护盾数
              var last_bomb_count = res.data.data.last_bomb_count; //用户本场已使用空袭次数
              var last_shield_count = res.data.data.last_shield_count; //用户本场已使用护盾次数
              var max_bomb_count = that.data.max_bomb_count; //最大空袭数（本场）
              var max_shield_count = that.data.max_shield_count; //最大护盾数（本场）
              var temp_left_bomb_count = max_bomb_count - last_bomb_count; //用户本场剩余空袭次数）
              var temp_left_shield_count = max_shield_count - last_shield_count; //用户本场剩余护盾次数
              var final_bomb_count = minNum(temp_left_bomb_count, bomb_count); //前端显示空袭次数
              var final_shield_count = minNum(temp_left_shield_count, shield_count); //前端显示防空次数
              function minNum(a, b) {
                if (a > b) {
                  return b;
                } else {
                  return a;
                }
              }
              that.setData({
                left_duobao: left_duobao, //剩余进攻次数
                final_bomb_count: final_bomb_count, //显示的空袭次数
                final_shield_count: final_shield_count, //显示的护盾次数
              })
            } else {

            }
          },
          fail: function (res) {
            wx.hideLoading();
            wx.showToast({
              title: '网络错误',
              icon: 'none',
              mask: true,
            })
          }
        });

        // =============================================
      },
      fail: function (res) {
        wx.showLoading({
          title: '加载失败请重试',
        })

        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
      },
    })
   
  },
  onLoad: function(e) {
    var that = this;
    var war_id = 0;
    if (that.data.war_id) {
      war_id = that.data.war_id;
    } else {
      war_id = e.id;
      that.setData({
        war_id: e.id,
      });
    }

    wx.onSocketError((res) => {
      // console.log('WebSocket连接打开失败')
      this.linkSocket();
      this.reconnect()
    })

  },
  // 输入密码方法
  shurumima: function() {
    this.setData({
      showModal: true
    })
  },
  // socket链接
  linkSocket: function() {
    let that = this
    wx.connectSocket({
      url: "wss://master.shoppingwar.cn/war",
      success() {
        // console.log('连接成功')
        var shuju = {
          type: 'join',
          session_str: wx.getStorageSync('session_str'),
          war_id: that.data.war_id
        }
        shuju = that.base64_encode(JSON.stringify(shuju));

        wx.sendSocketMessage({
          data: shuju
          
        });
        that.initEventHandle()
      }
    });


  },
  // 第一次链接加入
  diyici: function() {
    var that = this;
    // console.log(this.data.diyici)
    if (this.data.diyici == 1) {
      var shuju = {
        type: 'join',
        session_str: wx.getStorageSync('session_str'),
        war_id: this.data.war_id
      }
      shuju = this.base64_encode(JSON.stringify(shuju));

      wx.sendSocketMessage({
        data: shuju,
       
      });
 
    }
  },
  // 绑定事件
  initEventHandle: function() {
    let that = this
    wx.onSocketMessage((res) => {
      //收到消息
      if (res.data == "ping") {
        heartCheck.reset().start()
      } else {
        that.chuli(res.data);
      }
    })
    wx.onSocketOpen(() => {
      console.log('WebSocket连接打开')
      heartCheck.reset().start();
      that.diyici();
      
    })
    wx.onSocketError((res) => {
      // console.log('WebSocket连接打开失败')
      that.linkSocket();
      that.reconnect()
    })
    wx.onSocketClose((res) => {
      console.log('WebSocket 已关闭！')
      // that.reconnect()
    })
  },
  // 断线重连
  reconnect: function() {
    var that = this;
    if (this.lockReconnect) return;
    that.lockReconnect = true;
    clearTimeout(this.timer)
    
    this.timer = setTimeout(() => {
      var shuju = {
        type: 'join',
        session_str: wx.getStorageSync('session_str'),
        war_id: that.data.war_id
      }
      shuju = that.base64_encode(JSON.stringify(shuju));
      wx.sendSocketMessage({
        data: shuju,
      
      });
      that.setData({
        diyici: 1
      })
      that.linkSocket();
      that.lockReconnect = false;
    }, 5000);
  },
  chuli: function(str) {
    var that = this;
    var shuju = that.base64_decode(str);
    var xinxi = {};
    shuju = JSON.parse(shuju);
    var listss = that.data.listss;
    var session_str = wx.getStorageSync('session_str'); //密钥
    var md5seen = utilMd5.md5(wx.getStorageSync('session_str'));
    shuju.msg = unescape(shuju.msg);

    switch (shuju.type) {
      case 'error':
        wx.showToast({
          title: shuju.msg,
          icon: 'none',
          duration: 2000
        });  
        switch (shuju.code) {
          case 1:
            that.hideModal111();
          case 2:
            wx.showModal({
              content: '您已没有弹药，是否去购买？',
              showCancel: true,
              cancelText: '取消',
              confirmText: '确定',
              success: function(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '../daoju/daoju',
                    success: function(res) {}
                  })
                }
              }
            })
            break;

          case 3:
            wx.showModal({
              content: '您已没有护盾，是否去购买？',
              showCancel: true,
              cancelText: '取消',
              confirmText: '确定',
              success: function(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '../daoju/daoju',
                    success: function(res) {}
                  })
                }
              }
            })
            break;
          case 4:
            wx.showModal({
              content: '您已没有炸弹，是否去购买？',
              showCancel: true,
              cancelText: '取消',
              confirmText: '确定',
              success: function(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '../daoju/daoju',
                    success: function(res) {}
                  })
                }
              }
            })
            break;
        }

        break;
      case 2:
        var war_id = that.data.war_id;
        // console.log(md5seen)
        if (shuju.md5_operator_str) {
          if (md5seen == shuju.md5_operator_str) {
            wx.request({
              url: url + 'War/userPropCount',
              data: {
                session_str: session_str,
                war_id: war_id,
                APP_ID: APP_ID,
                sign: md5([
                  "session_str" + session_str,
                  "war_id" + war_id,
                  "APP_ID" + APP_ID,
                ])
              },
              header: {},
              method: 'post',
              dataType: 'json',
              responseType: 'text',
              success: function(res) {
                wx.hideLoading();
                if (res.data.code == 200) {
                  var max_bullet_count = that.data.max_bullet_count; //最大进攻次数
                  var left_duobao = max_bullet_count - res.data.data.last_bullet_count; //剩余进攻次数
                  var have_bullet_count = res.data.data.have_bullet_count;//用户剩余夺宝次数
                  left_duobao = left_duobao - have_bullet_count < 0 ? left_duobao : have_bullet_count;//选择最小的夺宝次数
                  console.log(left_duobao)
                  var bomb_count = res.data.data.bomb_count; //用户剩余空袭数
                  var shield_count = res.data.data.shield_count; //用户剩余护盾数
                  var last_bomb_count = res.data.data.last_bomb_count; //用户本场已使用空袭次数
                  var last_shield_count = res.data.data.last_shield_count; //用户本场已使用护盾次数
                  var max_bomb_count = that.data.max_bomb_count; //最大空袭数（本场）
                  var max_shield_count = that.data.max_shield_count; //最大护盾数（本场）
                  var temp_left_bomb_count = max_bomb_count - last_bomb_count; //用户本场剩余空袭次数）
                  var temp_left_shield_count = max_shield_count - last_shield_count; //用户本场剩余护盾次数
                  var final_bomb_count = minNum(temp_left_bomb_count, bomb_count); //前端显示空袭次数
                  var final_shield_count = minNum(temp_left_shield_count, shield_count); //前端显示防空次数
                  function minNum(a, b) {
                    if (a > b) {
                      return b;
                    } else {
                      return a;
                    }
                  }
                  that.setData({
                    left_duobao: left_duobao, //剩余进攻次数
                    final_bomb_count: final_bomb_count, //显示的空袭次数
                    final_shield_count: final_shield_count, //显示的护盾次数
                  })
                }
              },
              fail: function(res) {
                wx.hideLoading();
                wx.showToast({
                  title: '网络错误',
                  icon: 'none',
                  mask: true,
                })
              }
            });
          }
        }
        that.setData({
          scoreid: shuju.head_img
        })
        if (md5seen == shuju.md5_session_str) {
          // 一样说明是自己发的
          // console.log('是自己发送消息');
          xinxi = {
            someone: 2,
            head_image: shuju.head_img,
            msg: shuju.msg,
            nickname: shuju.nick_name
          }
        } else {
          // console.log('不是自己发消息');
          xinxi = {
            someone: 1,
            head_image: shuju.head_img,
            msg: shuju.msg,
            nickname: shuju.nick_name
          }
        }
        if (shuju.hasOwnProperty("last_time")) {
          let zcsj = this.data.zhanchangshuju;
          zcsj.last_time = shuju.last_time;
          zcsj.start_fee = shuju.current_fee
          this.setData({
            zhanchangshuju: zcsj
          })
          if (shuju.last_time>0){
            that.setData({
              daojishi:1
            })
          }
          clearInterval(that.interval);
          that.qudaojishi();
        }
        if (shuju.hasOwnProperty("current_name")) {
          // current_fee
          let zcsj = that.data.zhanchangshuju;
          zcsj.last_time = shuju.last_time;
          zcsj.start_fee = shuju.current_fee;
          zcsj.current_name = shuju.current_name;
          that.setData({
            zhanchangshuju: zcsj
          })
          clearInterval(that.interval);
          that.qudaojishi();
        }
        break;
      case 8:
        // hbxx
        that.setData({
          warend:true,  //todo 战场结束
          hbxx: shuju,
          zhongjiang: true
        })
        break;
      case 9:
        that.setData({
          warend: true,  //todo 战场结束
          wz: shuju,
          wuzi: true
        })
        break;
      case 10:
        if (md5seen == shuju.md5_session_str) {
          switch (shuju.is_banned) {
            case 0:
              // 解除禁言
              var jy = that.data.zhanchangshuju;
              jy.is_banned = 0;
              that.setData({
                zhanchangshuju: jy
              })
              break;
            case 1:
              // 禁言
              var jy = that.data.zhanchangshuju;
              jy.is_banned = 1;
              that.setData({
                zhanchangshuju: jy
              })
              break;
          }
        }
        break;   
    }
    if (judgeObj(xinxi)){
      if (listss.length >= 15) {
        listss.splice(0, 1)
      }
      listss.push(xinxi); 
    } 
    function judgeObj(obj){
      for (var a in obj) {
        return true
      }
      return false
    }
   
    that.setData({
      listss: listss
    })
  },
  // 聊天
  liaotian: function() {
  },
  // 页面渲染完成后 调用
  onReady: function() {
    var that =this;
    wx.onNetworkStatusChange(function (res) {
      wx.closeSocket({});
      var networkType = that.data.networkType;
      console.log(res)
      if (networkType != res.networkType) {
        that.setData({
          networkType: res.networkType
        })
        wx.showLoading({
          title: '网络切换中',
          mask: true,
        })
        if (res.isConnected) {
          that.linkSocket();
          wx.hideLoading();
        }
      }
    })
  },
  onPullDownRefresh: function() {
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {     
  },
  onHide: function() {
   
    var that =this;
    wx.closeSocket();
    clearInterval(that.interval);
    clearTimeout(that.zzk_adds)
    clearTimeout(that.zzk_add)
  },
  onUnload: function() {
    var that = this;
    wx.closeSocket();
    clearInterval(that.interval);
    clearTimeout(that.zzk_adds)
    clearTimeout(that.zzk_add)
  },
  //cell事件处理函数
  bindCellViewTap: function(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../babyDetail/babyDetail?id=' + id
    });
  },
  //以下为密码弹窗的方法
  showDialogBtn: function() {
    this.setData({
      showModal: true
    })
  },
  /**
   * 用户输入的密码
   */
  inputChange: function(e) {
    this.setData({
      userpas: e.detail.value
    })
  },
  /**
   * 弹出框蒙层截断touchmove事件
   */
  preventTouchMove: function() {},
  /**
   * 隐藏模态对话框
   */
  hideModal: function() {
    this.setData({
      showModal: false
    });
  },
  /**
   * 对话框取消按钮点击事件
   */
  onCancel: function() {
    wx.navigateBack({
      delta: 1,
    })
  },
  /**
   * 对话框确认按钮点击事件(输入密码成功后进入战场)
   */
  onConfirm: function() {
    var war_id = this.data.war_id;
    var pwd = this.data.userpas;
    var that = this;
    wx.request({
      url: 'https://master.shoppingwar.cn/api/War/joinWar',
      data: {
        war_id: war_id,
        session_str: wx.getStorageSync('session_str'),
        pwd: pwd
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: function(res) {
        if (res.data.code == 200) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          });
          that.linkSocket();
          that.hideModal();
      
        } else {
          wx.navigateBack({
            delta: 1,
          })
          const wxCurrPage = getCurrentPages(); //获取当前页面的页面栈
          const wxPrevPage = wxCurrPage[wxCurrPage.length - 2]; //获取上级页面的page对象
          if (wxPrevPage) {
            //修改上级页面的数据
            wxPrevPage.setData({
              zzk: 2,
              bwl: res.data.msg //baseData为上级页面的某个数据
            })
          }
        }
      },
      fail: function(res) {},
    })


  },
  // 预约进攻弹窗
  /**
   * 隐藏模态对话框
   */
  hideModal1: function() {
    this.setData({
      yuyue: false
    });
  },
  // 预约进攻弹窗点击护盾的对勾
  hudun: function(e) {
    if (e.target.dataset.shield == 0) {
      // 说明点击时 对勾是灰色的 
      this.setData({
        is_shield: 1
      })
    } else {
      // 说明点击时 对勾是红色的
      this.setData({
        is_shield: 0
      })
    }
  },
  // 预约进攻弹窗点击加减号
  yuyuejingong: function(e) {
    if (e.target.dataset.type == 1) {
      // 点击减号
      var shuliang = this.data.jingongcishu - 1;
      if (shuliang <= 0) {
        shuliang = 0
      }
      this.setData({
        jingongcishu: shuliang
      })
    } else {
      // 点击加号
      var shuliang = this.data.jingongcishu + 1;
      if (shuliang > this.data.zhanchangshuju.last_bullet_count) {
        wx.showToast({
          title: '已达本次战场最大预约夺宝次数',
          icon: 'none',
          duration: 1000
        });
        shuliang = shuliang - 1;
      }
      this.setData({
        jingongcishu: shuliang
      })
    }
  },
  // 显示预约进攻弹窗
  xianshiyuyue: function(e) {
    var session_str = wx.getStorageSync('session_str'); ///获取密钥
    var form_id = e.detail.formId; //formId
    //加入formid 借口
    wx.request({
      url: url + 'User/getFormId',
      data: {
        session_str: session_str,
        form_id: form_id,
        APP_ID: APP_ID,
        sign: md5([
          "session_str" + session_str,
          "form_id" + form_id,
          "APP_ID" + APP_ID
        ])
      },
      header: {},
      method: 'post',
      dataType: 'json',
      responseType: 'text',
      success: function(res) {

      },
      fail: function(res) {

      },
    })
    this.setData({
      yuyue: true
    })
  },
  escapeChars: function(str) {
    str = str.replace(/&/g, '&amp;');
    str = str.replace(/</g, '&lt;');
    str = str.replace(/>/g, '&gt;');
    str = str.replace(/'/g, '&acute;');
    str = str.replace(/"/g, '&quot;');
    str = str.replace(/\|/g, '&brvbar;');
    return str;
  },
  // 提交预约
  tijiao: function() {
    var war_id = this.data.war_id;
    var bullet_count = this.data.jingongcishu;
    // var is_shield = this.data.is_shield;
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    var that = this;
    wx.request({
      url: 'https://master.shoppingwar.cn/api/War/reserveWar',
      data: {
        war_id: war_id,
        session_str: wx.getStorageSync('session_str'),
        bullet_count: bullet_count,
        // is_shield: is_shield
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: function(res) {
        if (res.data.code == 200) {
          wx.hideLoading();
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          });
          that.setData({
            jingongcishu: 0
          })
          that.hideModal1();
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          });
        }

        wx.request({
          url: 'https://master.shoppingwar.cn/api/War/warInfo',
          data: {
            war_id: war_id,
            session_str: wx.getStorageSync('session_str')
          },
          method: 'POST',
          dataType: 'json',
          responseType: 'text',
          success: function(res) {
            that.setData({
              last_bullet_count: res.data.data.last_bullet_count, //剩余进攻次数
              max_bullet_count: res.data.data.max_bullet_count, //最大进攻次数
              max_bomb_count: res.data.data.max_bomb_count, //最大空袭数（本场）
              max_bomb_count: res.data.data.max_shield_count, //最大护盾数（本场）
            })
            that.setData({
              zhanchangshuju: res.data.data,
            })

          },
        })
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  hideModal111: function() {
    this.setData({
      zhanchanghongbao: false
    });
  },
  hideModal11111: function() {
    this.setData({
      wuzi: false
    });
  },
  hideModal1111: function() {
    this.setData({
      zhongjiang: false
    });
  },
  hideModal11: function() {
    this.setData({
      zhanchangxinxi: false
    });
  },
  // 显示信息（战场信息）
  xianshixinxi: function() {
    this.setData({
      zhanchangxinxi: true
    });
  },
  // 跳转拍卖指南
  paimaizhinan: function() {
    wx.navigateTo({
      url: '../zhinan/zhinan',
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  // 跳转战斗回放
  zhandouhuifangt: function() {
    wx.navigateTo({
      url: '../huifang/huifang?id=' + this.data.war_id,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  // 红包领取
  hongbaolingqu: function() {
    var that =this;
    // 点击领取红包
    var shuju = {
      type: 5,
      session_str: wx.getStorageSync('session_str'),
      war_id: this.data.war_id
    }
    shuju = this.base64_encode(JSON.stringify(shuju));
    wx.sendSocketMessage({
      data: shuju,
      fail() {
        that.reconnect()
      }
    });
  },
  // 点击红包
  dianjihongbao: function() {
    var that = this;
    wx.request({
      url: url+'War/getWarRedpack',
      data: {
        war_id: this.data.war_id
      },
      header: {},
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: function(res) {
        that.setData({
          hongbaoxinxi: res.data.data
        })
      },
      fail: function(res) {},
      complete: function(res) {},
    })
    this.setData({
      zhanchanghongbao: true
    });
  },
  // 倒计时时间
  daojishijisuan: function(e) {
    var that = this;
    var zzk_data = wx.getStorageSync('zzk_data');
    var xitongshijian = Date.parse(new Date()) - zzk_data*1000;
    var shengyushijian = e.start_time * 1000 - xitongshijian;
    shengyushijian = shengyushijian / 1000;
    var zhanchangshuju = that.data.zhanchangshuju;
    if (shengyushijian > 60) {
      shengyushijian = shengyushijian - 60;
      that.zzk_add =  setTimeout(function() {
        wx.showToast({
          title: '距离战场开始还有60秒',
          icon: 'none',
          duration: 2000
        });
        that.zzk_adds= setTimeout(function() {
          let start = 1;
          that.shuaxinshuju(start);
        }, 60000);
      }, shengyushijian * 1000);
    } else if (shengyushijian <= 60 && shengyushijian > 0) {
      that.zzk_add = setTimeout(function() {
        let start = 1;
        that.shuaxinshuju(start);
      }, shengyushijian * 1000);
    } 
    // that.setData({
    //   djsj: zhanchangshuju.last_time
    // })
  },
  qudaojishi: function () {
    clearInterval(this.interval);
    var that = this;
    var totalSecond = that.data.zhanchangshuju.last_time;
    console.log(totalSecond)
    var sj = this.data.zhanchangshuju.start_time;
    sj = Date.parse(sj);
    var timestamp = Date.parse(new Date());
    if (sj > timestamp) {
    } else if (sj == NaN) {
    } else {
      this.interval = setInterval(function () {
        if (totalSecond>0){
          that.setData({
            daojishi:1
          })
        }
        that.setData({
          djsj: totalSecond
        })
        if (totalSecond < 0 && sj < timestamp) {
          clearInterval(this.interval);
          wx.showToast({
            title: '活动已结束',
            icon: 'none',
          });
          return false;
        }
        if (totalSecond <= 0) {
          clearInterval(this.interval);
          return false;
        }
        totalSecond--;
      }.bind(that), 1000);
    }
  },
  // 倒计时
  // qudaojishi: function() {  
  //   var that = this;
  //   var totalSecond = that.data.zhanchangshuju.last_time;
  //   var sj = this.data.zhanchangshuju.start_time;
  //   sj = Date.parse(sj);
  //   var timestamp = Date.parse(new Date());
  //   if(!zzk_date){
  //     zzk_date =0
  //   }
  //   if (sj > timestamp) { 
  //   } else if (sj == NaN) {
  //   } else {
  //     clearInterval(that.data.interval)
  //     that.data.interval = setInterval(function() {
  //       that.setData({
  //         djsj: zzk_date
  //       })
  //       if (zzk_date <= 0) {
  //         zzk_date =0
  //         }else{
  //         zzk_date--;
  //         }
  //     }, 1000);
  //   }
  // },
  // 刷新数据
  shuaxinshuju: function(arg) {
    var that = this;
    wx.request({
      url: url+'War/warInfo',
      data: {
        war_id: that.data.war_id,
        session_str: wx.getStorageSync('session_str')
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: function(res) {
        res.data.data.start_time = that.format(res.data.data.start_time * 1000);
        that.setData({
          zhanchangshuju: res.data.data,
        })
        if (arg) {
          that.setData({
            daojishi: 1,
          })
          clearInterval(that.interval);
          that.qudaojishi();
        }
        // 请求用户信息接口数据、
        wx.request({
          url: url + 'War/userPropCount',
          data: {
            session_str: wx.getStorageSync('session_str'),
            war_id: that.data.war_id,
            APP_ID: APP_ID,
            sign: md5([
              "session_str" + wx.getStorageSync('session_str'),
              "war_id" + that.data.war_id,
              "APP_ID" + APP_ID,
            ])
          },
          header: {},
          method: 'post',
          dataType: 'json',
          responseType: 'text',
          success: function (res) {
            wx.hideLoading();
            if (res.data.code == 200) {
              var max_bullet_count = that.data.max_bullet_count; //最大进攻次数
              var left_duobao = max_bullet_count - res.data.data.last_bullet_count; //剩余进攻次数
              var have_bullet_count = res.data.data.have_bullet_count;//用户剩余夺宝次数
              left_duobao = left_duobao - have_bullet_count < 0 ? left_duobao : have_bullet_count;//选择最小的夺宝次数
              console.log(left_duobao)
              var bomb_count = res.data.data.bomb_count; //用户剩余空袭数
              var shield_count = res.data.data.shield_count; //用户剩余护盾数
              var last_bomb_count = res.data.data.last_bomb_count; //用户本场已使用空袭次数
              var last_shield_count = res.data.data.last_shield_count; //用户本场已使用护盾次数
              var max_bomb_count = that.data.max_bomb_count; //最大空袭数（本场）
              var max_shield_count = that.data.max_shield_count; //最大护盾数（本场）
              var temp_left_bomb_count = max_bomb_count - last_bomb_count; //用户本场剩余空袭次数）
              var temp_left_shield_count = max_shield_count - last_shield_count; //用户本场剩余护盾次数
              var final_bomb_count = minNum(temp_left_bomb_count, bomb_count); //前端显示空袭次数
              var final_shield_count = minNum(temp_left_shield_count, shield_count); //前端显示防空次数
              function minNum(a, b) {
                if (a > b) {
                  return b;
                } else {
                  return a;
                }
              }
              that.setData({
                left_duobao: left_duobao, //剩余进攻次数
                final_bomb_count: final_bomb_count, //显示的空袭次数
                final_shield_count: final_shield_count, //显示的护盾次数
              })
            }
            // 用户数据结束
          },
          fail: function (res) {
            wx.hideLoading();
            wx.showToast({
              title: '网络错误',
              icon: 'none',
              mask: true,
            })
          }
        });
      },
    })
  },
  /**
   * 分享
   */
  onShareAppMessage: function(res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮

    }
    return {
      title: '购物战场',
      path: 'pages/index/index',
    }
  }
})